package org.hk.proxy.client.handlers;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import org.hk.proxy.common.constant.CommonKey;
import org.hk.proxy.protocol.ProxyMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class RealServerChannelHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private static final Logger log = LoggerFactory.getLogger(RealServerChannelHandler.class);
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg){
        try {
            Channel realServerChannel = ctx.channel();
            Channel proxyChannel =  realServerChannel.attr(CommonKey.REAL_PROXY).get();
            byte[] bytes = new byte[msg.readableBytes()];
            msg.readBytes(bytes);
            if(proxyChannel==null){
                log.error("proxyChannel is null:{}",ctx.channel());
                ctx.channel().close();
            }else {
                ProxyMessage proxyMessage = new ProxyMessage();
                proxyMessage.setType(ProxyMessage.P_TYPE_TRANSFER);
                proxyMessage.setData(bytes);
                proxyMessage.setSerialNumber(ctx.channel().attr(CommonKey.SID).get());
                proxyChannel.writeAndFlush(proxyMessage);
            }
        }catch (Exception e){
            try {
                log.error("realChannel read error:",e);
                channelInactive(ctx);
            } catch (Exception ex) {
                ctx.channel().close();
            }
        }
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        Channel realServerChannel = ctx.channel();
        Channel proxyChannel = realServerChannel.attr(CommonKey.REAL_PROXY).get();
        if (proxyChannel != null) {
            proxyChannel.config().setOption(ChannelOption.AUTO_READ, realServerChannel.isWritable());
        }
        super.channelWritabilityChanged(ctx);
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("real server connect : {}",ctx.channel());
        super.channelActive(ctx);
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel realServerChannel = ctx.channel();
        Channel proxyChannel = realServerChannel.attr(CommonKey.REAL_PROXY).getAndSet(null);
        log.error("real server lost connection");
        if(proxyChannel!=null){
            proxyChannel.attr(CommonKey.REAL_PROXY).set(null);
            ProxyMessage proxyMessage = new ProxyMessage();
            proxyMessage.setType(ProxyMessage.TYPE_DISCONNECT);
            proxyChannel.writeAndFlush(proxyMessage);
        }
        super.channelInactive(ctx);
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if(cause instanceof IOException){
            channelInactive(ctx);
        }else {
            super.exceptionCaught(ctx, cause);
        }
    }
}
